﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Net.Sockets;

namespace HttpServer
{
    public partial class HttpServer : Form
    {
        private int a_serverPort = 4444;

        private HTTPListener.VVHttpListener a_httpListener;


        public HttpServer()
        {
            InitializeComponent();

            a_httpListener = new HTTPListener.VVHttpListener();
            a_httpListener.RequestReceived += new EventHandler<HTTPListener.VVHttpListener.HttpContentEventArgs>(vvListener_RequestReceived);

            a_httpListener.Start(a_serverPort);
        }


        //Event handler for receiving the http requests
        void vvListener_RequestReceived(object sender, HTTPListener.VVHttpListener.HttpContentEventArgs e)
        {
            string displaytext = "";
            displaytext += "received a http request " + e.Url + "\n";
            string[] args = e.Body.Split(new char[] { '=', '&' });
           

           
            if (richTextBox1.InvokeRequired)
                richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(displaytext); }));
        }

        
        /// <summary>
        /// Example for sending a http post request
        /// </summary>
        /// <param name="httpAddress"></param>
        private void SendRequest(string httpAddress) 
        {
            WebRequest request = WebRequest.Create(httpAddress);
            request.Method = "POST";

            string postData = "";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);


            request.ContentType = "application/x-www-form-urlencoded";           
            request.ContentLength = byteArray.Length;
            request.ContentType = "text/xml";
            // Get the request stream.
            using (Stream dataStream = request.GetRequestStream())
            {
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
        }

        
        /// <summary>
        /// Stop the listener when closing the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HttpServer_FormClosing(object sender, FormClosingEventArgs e)
        {
           a_httpListener.Stop();
        }
      
       
        
    }
}
